<script setup lang="tsx">
import {
  inviteBusinessUrlListApi,
  inviteBusinessUrlDeleteApi,
  inviteBusinessDetailListApi,
  inviteBusinessUrlDownloadApi
} from '@/api/merchantManagement'
import type { InviteBusinessDetailListParams } from '@/api/merchantManagement/types'
import Write from './components/Write.vue'
import { ElButton } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import { InviteStateDict, dictToList } from '@/utils/dict'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await inviteBusinessUrlListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list:
        res.data.list.map((item) => {
          item.isLongEffective = item.urlValidDay == 0
          return item
        }) || [],
      total: res.data.total || 0
    }
  },
  fetchDelApi: async () => {
    const res = await inviteBusinessUrlDeleteApi(unref(ids.value[0]))
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const isLongDay = ref(false)
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: 'ID',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'inviteName',
    label: '链接名称',
    width: 380,
    search: {
      componentProps: {
        placeholder: '请输入链接名称'
      }
    },
    form: {
      colProps: {
        span: 24
      }
    }
  },
  // {
  //   field: 'equity',
  //   label: '链接权益',
  //   width: 150,
  //   form: {
  //     hidden: true
  //   },
  //   search: {
  //     hidden: true
  //   },
  //   table: {
  //     slots: {
  //       default: (data: any) => {
  //         const row = data.row as any
  //         return (
  //           <>
  //             <div>发布次数:{row.activeCount}</div>
  //             <div>经纪人:{row.activeCount}</div>
  //           </>
  //         )
  //       }
  //     }
  //   }
  // },
  {
    field: 'activeCount',
    label: '发布次数',
    form: {
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '50%'
        },
        type: 'number',
        slots: {
          append: () => <span>次</span>
        }
      }
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'remark',
    label: '备注',
    form: {
      colProps: {
        span: 24
      }
    },
    search: {
      hidden: true
    }
  },
  // {
  //   field: 'userCount',
  //   label: '经纪人数',
  //   form: {
  //     colProps: {
  //       span: 24
  //     },
  //     componentProps: {
  //       style: {
  //         width: '50%'
  //       },
  //       type: 'number',
  //       slots: {
  //         append: () => <span>人</span>
  //       }
  //     }
  //   },
  //   search: {
  //     hidden: true
  //   },
  //   table: {
  //     hidden: true
  //   }
  // },
  {
    field: 'state',
    label: t('userDemo.status'),
    form: {
      hidden: true
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dictToList(InviteStateDict)
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>{row.state && InviteStateDict[row.state]}</span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'urlValidDay',
    label: '链接有效期',
    width: 140,
    formatter: (record: Recordable) => {
      return record.urlValidDay == 0 ? '长期有效' : `${record.urlValidDay}天`
    },
    form: {
      colProps: {
        span: 12
      },
      componentProps: {
        disabled: false,
        style: {
          width: '100%'
        },
        type: 'number',
        slots: {
          append: () => <span>天</span>
        }
      }
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'isLongEffective', // 是否长期有效
    label: '',
    hidden: true,
    labelWidth: 0,
    form: {
      colProps: {
        span: 12
      },
      component: 'CheckboxGroup',
      componentProps: {
        options: [{ label: '长期有效', value: true }],
        on: {
          change: (value) => {
            const isLongEffectiveFormSchema = allSchemas.formSchema.at(4)
            // 将isLongEffective设置成24份占满
            isLongEffectiveFormSchema!.colProps = { span: value.length > 0 ? 24 : 12 }
            isLongEffectiveFormSchema!.label = value.length > 0 ? '链接有效期' : ''
            const urlValidDayFormSchema = allSchemas.formSchema.at(3)
            urlValidDayFormSchema!.hidden = value.length > 0
            writeRef.value?.setValues({ urlValidDay: value.length > 0 ? 0 : '' })
          }
        }
      }
    },
    search: {
      hidden: true
    }
  },
  // {
  //   field: 'trialDay',
  //   label: '试用期',
  //   form: {
  //     colProps: {
  //       span: 24
  //     }
  //   },
  //   search: {
  //     hidden: true
  //   }
  // },
  {
    field: 'settleSuccessCount',
    label: '成功入驻数',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'createTime',
    label: t('userDemo.createTime'),
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 180
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 250,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <ElButton type="primary" link onClick={() => downloadFile(row)}>
                下载二维码
              </ElButton>
              {/* <a href={row.miniImgUrl} download="lxy.jpg">
                <ElButton type="primary" link>
                  下载二维码
                </ElButton>
              </a> */}
              <ElButton
                v-hasPermi="POST /inviteBusinessUrl/delete"
                type="danger"
                link
                onClick={() => delData(row)}
              >
                {t('exampleDemo.del')}
              </ElButton>
              <ElButton
                v-hasPermi="GET /inviteBusinessUrl/pageEnterBusiness"
                type="primary"
                link
                onClick={() => details(row)}
              >
                查看入驻商家
              </ElButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  console.log(params)
  const { createTime, ...rest } = params
  let startTime, endTime
  if (createTime && createTime.length > 0) {
    startTime = createTime[0]
    endTime = createTime[1]
  }
  currentPage.value = 1
  searchParams.value = {
    startTime,
    endTime,
    ...rest
  }
  getList()
}

const showDrawer = ref(false)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<InviteBusinessDetailListParams>()
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  allSchemas.formSchema.at(1)!.hidden = false
  actionType.value = ''
  isLongDay.value = false
}

const delLoading = ref(false)
const ids = ref<number[]>([])

const downloadFile = async (row?: any) => {
  const res = await inviteBusinessUrlDownloadApi(row.id)
  console.log(res.data)
  const correctMimeType = 'image/png'
  const url = window.URL.createObjectURL(new Blob([res.data], { type: correctMimeType }))
  console.log(url)
  const fileName = row.inviteName
  let link = document.createElement('a')
  link.href = url
  link.download = fileName
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const delData = async (row?: InviteBusinessDetailListParams) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.id]
    : elTableExpose?.getSelectionRows().map((v: InviteBusinessDetailListParams) => v.id) || []
  delLoading.value = true

  await delList(unref(ids).length, '确认删除该邀请链接？').finally(() => {
    delLoading.value = false
  })
}

const detailInviteCode = ref('')
const details = async (row: any) => {
  console.log(row)
  detailInviteCode.value = row.inviteCode
  getDetailList()
  showDrawer.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

// 链接入驻详情表格
const {
  tableRegister: detailTableRegister,
  tableState: detailTableState,
  tableMethods: detailTableMethods
} = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = detailTableState
    const res = await inviteBusinessDetailListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      inviteCode: detailInviteCode.value
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  }
})

const { getList: getDetailList } = detailTableMethods

const detailCrudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: 'ID',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'businessName',
    label: '入驻商家名称',
    form: {
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'createTime',
    label: '创建时间',
    form: {
      hidden: true
    }
  }
])

const { allSchemas: allDetailSchemas } = useCrudSchemas(detailCrudSchemas)

const {
  total: detailTotal,
  loading: detailLoading,
  dataList: detailList,
  pageSize: detailPageSize,
  currentPage: detailCurrentPage
} = detailTableState

const save = async () => {
  saveLoading.value = true
  const write = unref(writeRef)
  const res = await write?.submit()
  saveLoading.value = false
  allSchemas.formSchema.at(3)!.hidden = false
  const isLongEffectiveFormSchema = allSchemas.formSchema.at(4)
  // 将isLongEffective设置成24份占满
  isLongEffectiveFormSchema!.colProps = { span: 12 }
  isLongEffectiveFormSchema!.label = ''
  if (!res) {
    return
  }
  write?.reset()
  dialogVisible.value = false
  getList()
}

const onCloseDrawer = () => {
  dialogVisible.value = false
  console.log(allSchemas.formSchema.at(3))
  allSchemas.formSchema.at(3)!.hidden = false
  const isLongEffectiveFormSchema = allSchemas.formSchema.at(4)
  // 将isLongEffective设置成24份占满
  isLongEffectiveFormSchema!.colProps = { span: 12 }
  isLongEffectiveFormSchema!.label = ''
  const write = unref(writeRef)
  write?.reset()
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px">
      <Search
        :schema="allSchemas.searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
      />

      <div class="mb-10px">
        <ElButton v-hasPermi="'POST /admin/user/create'" type="success" @click="AddAction">
          <ElIcon><Plus /></ElIcon>
          {{ t('MerchantManagement.createInvitationLink') }}
        </ElButton>
      </div>
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>

    <ElDrawer v-model="dialogVisible" :title="dialogTitle" size="650px" @close="onCloseDrawer">
      <Write ref="writeRef" :form-schema="allSchemas.formSchema" :current-row="currentRow" />
      <template #footer>
        <ElButton
          v-hasPermi="'POST /inviteBusinessUrl/save'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          {{ t('exampleDemo.save') }}
        </ElButton>
        <ElButton @click="onCloseDrawer">{{ t('dialogDemo.close') }}</ElButton>
      </template>
    </ElDrawer>

    <ElDrawer
      title="链接入驻详情"
      v-model="showDrawer"
      direction="rtl"
      size="650px"
      @close="showDrawer = false"
    >
      <Table
        v-model:current-page="detailCurrentPage"
        v-model:page-size="detailPageSize"
        :columns="allDetailSchemas.tableColumns"
        :data="detailList"
        :loading="detailLoading"
        @register="detailTableRegister"
        :pagination="{
          total: detailTotal
        }"
      />
    </ElDrawer>
  </div>
</template>
